package org.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dbi.beans.Attribute;
import org.dbi.rdbms.Rdbms;

/**
 * Servlet implementation class RdbmsServlet
 */
@WebServlet("/RdbmsServlet")
public class RdbmsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final int CREATE_DATABASE = 1;
	public static final int CREATE_TABLE = 1;
	public static final int SELECT_QUERY = 1;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RdbmsServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int command = Integer.parseInt(request.getParameter("submit"));
		String destination = null;
		if (command == CREATE_DATABASE) {
			if (!checkEmtyParameter(request, "createDatabase"))
				request.getSession().setAttribute(
						"result",
						createDatabase((String) getRequestParameterResult(
								request, "createDatabase")));
			destination = "showdatabases.jsp";
		}

		if (command == SELECT_QUERY) {
			if (!checkEmtyParameter(request, "query")) {
				request.getSession().setAttribute("queryString",
						request.getParameter("query"));
				request.getSession().setAttribute("queryResult",
						getQueryResult(request.getParameter("query")));
				System.out.println(" Select Query");
			}
			destination = "select.jsp";
		}
		response.sendRedirect(response.encodeRedirectURL(destination));
	}

	public boolean checkEmtyParameter(HttpServletRequest request,
			String parmNaam) {
		return request.getParameter(parmNaam) == null;
	}

	public Object getRequestParameterResult(HttpServletRequest request,
			String parmNaam) {
		return request.getParameter(parmNaam);
	}

	public String createDatabase(String dbNaam) {
		return Rdbms.getInstance().createDatabase(dbNaam);
	}

	private ArrayList<Attribute> getQueryResult(String query) {
		return null;
	}
}
